package ynu.edu.Util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import ynu.edu.Service.Impl.CameraService;
import org.springframework.stereotype.Component;
import ynu.edu.Service.YsToken;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
import java.util.UUID;

@Component
public class CameraCaptureUtil {
    private static final String CAMERA_API_URL = "https://open.ys7.com/api/lapp/device/capture";
    private static final String IMAGE_SAVE_DIR = "src/main/resources/static/images/";

    @Resource
    private PropertiesUtil propertiesUtil;
    @Resource
    YsToken ysToken;
    @Resource
    CameraService cameraService;

    public void captureImage(String deviceSerial, int channelNo, int quality) {
        try {
            String accessToken = getAccessToken();
            while (accessToken == null || isTokenExpired()) {
                accessToken = ysToken.getAccessToken();
            }
            fetchAndSaveImage(deviceSerial, channelNo, quality, accessToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getAccessToken() {
        Properties properties = propertiesUtil.loadProperties();
        return properties.getProperty("ys_access_token");
    }

    private boolean isTokenExpired() {
        Properties properties = propertiesUtil.loadProperties();
        String expiresInMillis = properties.getProperty("ys_expires_Time");
        if (expiresInMillis == null) {
            return true;
        }
        long expiresAt = Long.parseLong(expiresInMillis);
        return System.currentTimeMillis() >= expiresAt;
    }

    private void fetchAndSaveImage(String deviceSerial, int channelNo, int quality, String accessToken) throws Exception {
        URL url = new URL(CAMERA_API_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setDoOutput(true);

        String requestBody = String.format("accessToken=%s&deviceSerial=%s&channelNo=%d&quality=%d",
                accessToken, deviceSerial, channelNo, quality);

        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = requestBody.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            try (InputStream is = connection.getInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                String jsonResponse = response.toString();

                // 解析JSON响应
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode rootNode = objectMapper.readTree(jsonResponse);
                JsonNode dataNode = rootNode.path("data");
                JsonNode picUrlNode = dataNode.path("picUrl");

                if (picUrlNode.isTextual()) {
                    String picUrl = picUrlNode.asText();
                    System.out.println("Image URL: " + picUrl);
                    downloadAndSaveImage(picUrl);
                } else {
                    System.err.println("Failed to find picUrl in response.");
                }
            }
        } else {
            System.err.println("Failed to capture image. Response Code: " + responseCode);
            try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.err.println("Error Response: " + response.toString());
            }
        }
    }
    private void downloadAndSaveImage(String imageUrl) throws IOException {
        // 确保保存目录存在
        File saveDir = new File(IMAGE_SAVE_DIR);
        if (!saveDir.exists()) {
            saveDir.mkdirs();
        }

        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 生成唯一的文件名
            String fileName = UUID.randomUUID().toString() + ".jpg";
            String filepath = "/images/"+fileName;
            cameraService.fetchUrl(filepath);
            try (InputStream is = connection.getInputStream();
                 FileOutputStream fos = new FileOutputStream(IMAGE_SAVE_DIR + fileName)) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, bytesRead);
                }
                System.out.println("Image saved successfully with filename: " + fileName);
            }
        } else {
            System.err.println("Failed to download image. Response Code: " + responseCode);
        }
    }
}
